def changelog_entry
  @changelog_entry ||=
    begin
      file = git.added_files.find { |path| path =~ %r{\Achangelogs/unreleased/} }

      YAML.safe_load(File.read(file))
    rescue
      # The change log danger file will handle this
      {}
    end
end

required_labels = %w[devops::create]
required_labels << "group::gitaly" if GITALY_TEAM.include?(gitlab.mr_author)

TYPE_TO_LABEL = {
  'added' => ['feature'],
  'fixed' => ['bug'],
  'changed' => ['backstage'],
  'deprecated' => ['backstage'],
  'security' => ['security'],
  'removed' => ['backstage'],
  'performance' => ['performance', 'backstage'],
  'other' => ['backstage'],
  nil => []
}

INHERIRABLE_LABELS = TYPE_TO_LABEL.values.flatten +  %w[Deliverable]

def inherited_labels
  gitlab.api
    .merge_request_closes_issues( gitlab.mr_json['project_id'], gitlab.mr_json['iid'])
    .flat_map { |i| i.labels }
    .compact
    .uniq
    .select { |label| INHERIRABLE_LABELS.include?(label) }
end

required_labels.concat(TYPE_TO_LABEL[changelog_entry["type"]])

mr_labels = gitlab.mr_labels | required_labels | inherited_labels
gitlab.api.update_merge_request(
  gitlab.mr_json['project_id'],
  gitlab.mr_json['iid'],
  labels: mr_labels.join(",")
)

# vim: ft=ruby
